<template>
  <div v-if="visible"
       class='publish-container'>
    <el-dialog :visible.sync="visible"
               title="修改应用"
               :close-on-click-modal="false"
               @close="dialogClose">
      <el-form :model="editAppForm"
               :rules="formRules"
               ref="appForm"
               label-width="90px">
        <el-form-item label="应用名称"
                      prop="app_name">
          <el-input v-model="editAppForm.app_name"
                    placeholder="请输入应用名称">
          </el-input>
        </el-form-item>
        <el-form-item label="应用描述"
                      prop="app_des">
          <el-input v-model="editAppForm.app_des"
                    placeholder="请输入应用描述"
                    type="textarea">
          </el-input>
        </el-form-item>
        <el-form-item label="应用分组"
                      prop="app_group">
          <el-select v-model="editAppForm.app_group"
                     placeholder="请选择应用分组">
            <el-option v-for="item in appGroupCode"
                       :key="item.code_id"
                       :label="item.name"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <el-table :data="tableData"
                ref="table"
                :highlight-current-row="true"
                :header-cell-style="{background:'#f5f5f5'}"
                border
                style="width: 100%">
        <el-table-column type="index"
                         label="序号"
                         sortable
                         align="center"
                         width="100"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="name"
                         label="子权限项">
        </el-table-column>
        <el-table-column prop="business_field"
                         label="业务领域类别">
          <template slot-scope="scope">
            <el-select v-model="scope.row.business_field"
                       @change="changBusinessDialog"
                       multiple
                       placeholder="请选择">
              <el-option v-for="item in businessArea"
                         :key="item.value"
                         :label="item.name"
                         :value="item.value">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="manage_function"
                         label="管理职能类别">
          <template slot-scope="scope">
            <el-select v-model="scope.row.manage_function"
                       @change="changManageDialog"
                       multiple
                       placeholder="请选择">
              <el-option v-for="item in manageFunction"
                         :key="item.value"
                         :label="item.name"
                         :value="item.value">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogClose">取 消</el-button>
        <el-button @click="editApp"
                   type="primary">确 定</el-button>
      </div>
      <!-- 是否同步弹窗 -->
      <el-dialog title="同步"
                 :visible.sync="syncDialogVisible"
                 width="30%"
                 append-to-body>
        <span>是否需要同步？</span>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="syncDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="saveSync">确 定</el-button>
        </span>
      </el-dialog>
    </el-dialog>
  </div>
</template>
<script>


import { AppApi } from '@/services/settingManage'
import { standardCodeApi } from '@/services/StandardCode'
export default {
  data () {
    return {
      syncDialogVisible: false,
      businessval: '',
      manageval: '',
      business_field: [],
      manage_function: [],
      businessArea: [], //业务领域
      manageFunction: [], //管理职能
      tableData: [], //选择器
      visible: false,
      tag_list: [],
      editAppForm: {
        app_name: '',
        app_des: '',
        app_group: '',
        app_endpoint: '2',
        ascription: '1',
        ascription_company_id: '',
        app_url: '',
        logo: '',
        app_source: '1',
        source_id: '',
        screenshots: '',
        is_publish: '1',
        is_auth: '1'
      },
      formRules: {
        app_name: [
          { required: true, message: '请输入应用名称', trigger: 'blur' }
        ],
        app_des: [
          { required: true, message: '请输入应用描述', trigger: 'blur' }
        ]
      },
      resetForm: {
        app_name: '',
        app_des: '',
        app_group: '',
        app_endpoint: '2',
        ascription: '1',
        ascription_company_id: '',
        app_url: '',
        logo: '',
        app_source: '1',
        source_id: '',
        screenshots: '',
        is_publish: '1',
        is_auth: '1'
      },
      // 应用分组标准码
      appGroupCode: [],
      appGroupMap: new Map()
    }
  },
  props: {
    dialogVisible: {
      type: Boolean
    },
    dialogStatus: {
      type: String,
      default: "create"
    },
    dialogForm: {
      type: Object
    },
    callback: {
      type: Function
    }
  },
  watch: {
    dialogVisible (newval) {
      this.visible = newval;
    },
    dialogForm: {
      async handler (newval, oldval) {

        let temp = JSON.parse(JSON.stringify(newval));
        let reset = JSON.parse(JSON.stringify(this.resetForm))
        this.editAppForm = Object.assign(reset, temp)
        await this.getAppDetail(temp)
        this.editAppForm.logo = temp.logo
      },
      deep: true
    }
  },
  methods: {
    // 获取业务领域标准码
    getbusinessCode () {
      standardCodeApi.getCodeNoToken({
        data: {
          code_type: 'businessField',
          is_page: 0,
          system_no: "ass",
          no_token: "1"
        }
      }).then((res) => {
        this.businessArea = res.data.list
      }).catch((error) => {
        console.log(error)
      })
    },
    // 获取管理职能标准码
    getmanageCode () {
      standardCodeApi.getCodeNoToken({
        data: {
          code_type: 'manageFunction',
          is_page: 0,
          system_no: "ass",
           no_token: "1"
        }
      }).then((res) => {
        this.manageFunction = res.data.list
      }).catch((error) => {
        console.log(error)
      })
    },
    //修改权限项弹窗中的业务领域
    changBusinessDialog (val) {
      // console.log(val, '业务2');
      this.businessval = val.join(',')
    },
    //修改权限项中的管理职能
    changManageDialog (val) {
      // console.log(val, '管理2');
      this.manageval = val.join(',')
    },
    dialogClose () {
      this.$refs.appForm.resetFields();
      this.$emit("update:dialogVisible", false);
    },
    // 获取应用详情
    getAppDetail (temp) {
      return AppApi.getAppDetail({
        params: {
          // app_source: '1',
          app_id: temp.app_id
        }
      }).then(res => {
        if (res.code === 0) {
          console.log(res.data);
          let data = res.data
          this.editAppForm = Object.assign(this.editAppForm, data)
          let tag = res.data.tag_list
          for (let key in tag) {
            let business = []
            let manage = []
            if (JSON.stringify(tag[key]) !== '[]') {
              tag[key].businessField.forEach(item => {
                business.push(item.tag_value)
                this.tableData.forEach(item => {
                  if (item.type == key)
                    item.business_field = business
                })
              })
              tag[key].manageFunction.forEach(item => {
                manage.push(item.tag_value)
                this.tableData.forEach(item => {
                  if (item.type == key)
                    item.manage_function = manage
                })
                console.log(this.tableData, "表格");
              })
            } else {
              this.tableData.forEach(item => {
                item.business_field = []
                item.manage_function = []
              })
            }

          }
        }
      })
    },
    editApp () {
      this.$refs.appForm.validate((valid) => {
        if (valid) {
          if (this.editAppForm.app_no) {
            this.updateApp()
          } else {
            this.publishApp()
          }

        }
      })
    },
    // 修改app
    updateApp () {
      let newData = JSON.parse(JSON.stringify(this.tableData));
      newData.forEach(item => {
        item.business_field = item.business_field.join(',')
        item.manage_function = item.manage_function.join(',')
        delete item.name
      })
      let param = {
        app_id: this.editAppForm.app_id,
        app_group: this.editAppForm.app_group,
        app_name: this.editAppForm.app_name,
        app_des: this.editAppForm.app_des,
        tag_list: JSON.stringify(newData)
      }
      console.log(this.tableData);
      AppApi.updateApp({
        data: param
      }).then(res => {
        if (res.code === 0) {
          this.$message.success('修改应用成功')
          if (res.data.sync) {
            this.syncDialogVisible = true
          } else {
            this.dialogClose()
          }
          this.$emit('callback', '')

        }
      })
    },
    //确定同步
    saveSync () {
      AppApi.AppSync({
        data: {
          app_id: this.editAppForm.app_id,
        }
      }).then(res => {
        // console.log(res, 'edit')
        if (res.code === 0) {
          this.$message.success('同步权限成功')
          this.syncDialogVisible = false
          this.dialogClose()
        } else {

        }
      })
    },
    // 获取应用分组标准码
    getTypeCode () {
      return standardCodeApi.getCodeNoToken({
        data: {
          code_type: 'appOperateResourceType',
          is_page: 1,
          system_no: "ass",
          no_token: "1"
        }
      }).then(res => {
        if (res.code === 0 && res.data.list) {
          this.tableData = []
          res.data.list.map((item, index) => {
            let data = {
              type: item.value,
              name: item.name,
              business_field: [],
              manage_function: []
            }
            this.$set(this.tableData, index, data)
            // this.tableData.push(data)
          })

        }
      })
    },
    // 发布app(改)
    publishApp () {
      let userInfo = window.localStorage.getItem('userInfo') || '{}'
      userInfo = JSON.parse(userInfo)
      this.editAppForm.ascription_company_id = userInfo.comp_id
      this.editAppForm.source_id = this.editAppForm._id
      let newData = JSON.parse(JSON.stringify(this.tableData));
      newData.forEach(item => {
        item.business_field = item.business_field.join(',')
        item.manage_function = item.manage_function.join(',')
        delete item.name
      })
      let param = {
        app_group: this.editAppForm.app_group,
        app_name: this.editAppForm.app_name,
        app_des: this.editAppForm.app_des,
        tag_list: JSON.stringify(newData)
      }
      AppApi.publishApp({
        data: param
      }).then(res => {
        if (res.code === 0) {
          this.$message.success('发布应用成功')
          this.$emit('callback', '')
          this.dialogClose()
        }
      })
    },
    // 获取应用分组标准码
    getAppGroupCode () {
      return standardCodeApi.getCodeNoToken({
        data: {
          code_type: 'applicationGroup',
          is_page: 0,
          system_no: "ass",
          no_token: "1"
        }
      }).then(res => {
        if (res.code === 0 && res.data.list) {
          this.appGroupCode = res.data.list
          window.localStorage.setItem('appGroupCodeLocal', JSON.stringify(this.appGroupCode))
          this.convertCodeListToMap(this.appGroupMap, this.appGroupCode)
        }
      })
    },
    // 将标准码列表转换为map
    convertCodeListToMap (map, codeList) {
      codeList.map((item) => {
        map.set(item.value, item)
      })
    },
  },
  async created () {
    let appGroupCodeLocal = window.localStorage.getItem('appGroupCodeLocal')
    if (appGroupCodeLocal) {
      this.appGroupCode = JSON.parse(appGroupCodeLocal)
      this.convertCodeListToMap(this.appGroupMap, this.appGroupCode)
    } else {
      await this.getAppGroupCode()
    }
    this.getTypeCode()

    this.getbusinessCode()
    this.getmanageCode()
    await this.getAppGroupCode()
    // if (appGroupCodeLocal) {
    //   this.appGroupCode = JSON.parse(appGroupCodeLocal)
    //   this.convertCodeListToMap(this.appGroupMap, this.appGroupCode)
    // } else {
    //   await this.getAppGroupCode()
    // }
  },
  mounted () {
  }
}
</script>
<style scoped lang='scss'>
.publish-container {
  .el-select {
    width: 100%;
  }
}
</style>